const userCity = require('./utils/cityByLocation.js');
const initUser = require('./utils/initUser.js');
const wxCloudInit = require('./utils/wxCloudInit.js').wxCloudInit;

App({
  onLaunch: function (options) {
    this.globalData.launchOption = options;
    wx.showLoading({
      title: '正在定位位置',
      mask: true,
    })
    wx.getSetting({
      success: (res) => {
        let mockLocation = {
          longitude: 108.300476,
          latitude: 22.830934,
        };
        const failFunc = () => {
          wx.showToast({
            title: 'GPS定位失败，以南宁为参考城市,或手动选择城市',
            icon: 'none',
            image: '',
            duration: 2500,
            mask: false,
          })
          this.globalData.userLocation = mockLocation;
          this.globalData.userLocation.errMsg = 'mock';
        };
        const location = () => { // 定位方法
          console.log('定位开始');
          wx.getLocation({
            type: 'gcj02',
            altitude: true,
            success: (res) => {
              if (res.errMsg === "getLocation:ok") {
                this.globalData.userLocation = res;
                userCity(this, res.longitude, res.latitude);
                let pages = getCurrentPages();
                for(let i of pages){
                  if(i.route.indexOf('index/index') >= 0 ){
                    i.startPageLogic();
                  }
                }
              }
            },
            fail: function (res) {
              console.warn(res);
              failFunc();
            },
            complete: function (res) {
              console.log('定位结束');
              wx.hideLoading();
            },
          })
        };
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success: (res) => {
              location();
            },
            fail: function (res) { },
            complete: function (res) { },
          })
        } else {
          location();
        }
      },
      fail: function (res) {
        wx.showToast({
          title: JSON.stringify(res),
          icon: 'none',
          duration: 2000,
        })
       },
      complete: function (res) { 
        // console.log(res);
      },
    })
    initUser(this);
    wxCloudInit();
  },
  onShow(options) {
    // 测试教师 openid
    // options.query.offlineTid = "oIerT5HqOsjMxrjEPhtyudvJnmx8";
    if (options.query && options.query.offlineTid) {
      this.globalData.offlineTeacher = options.query.offlineTid;
      this.globalData.launchPage = 'offline';  
    }
    this.globalData.showOptions = options;
  },
  globalData: {
    login: null,
    userInfo: null,
    userLocation: null,
    userStudyInfo: null,
    userWxInfo: null,
    offlineTeacher: null,
    serverAddress: 'https://www.haitunxueche.com/',
    ossLink:'https://htxc.oss-cn-shenzhen.aliyuncs.com/',
    launchPage:'index',
  },
})